package com.hmdp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.lang.UUID;
import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.dto.LoginFormDTO;
import com.hmdp.dto.Result;
import com.hmdp.dto.UserDTO;
import com.hmdp.entity.User;
import com.hmdp.mapper.UserMapper;
import com.hmdp.service.IUserService;
import com.hmdp.utils.RegexUtils;
import com.hmdp.utils.UserHolder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.data.redis.connection.BitFieldSubCommands;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import static com.hmdp.utils.RedisConstants.*;
import static com.hmdp.utils.SystemConstants.USER_NICK_NAME_PREFIX;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Slf4j
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    /**
     * 发送验证码
     * @param phone
     * @param session
     * @return
     */
    @Override
    public Result sendCode(String phone, HttpSession session) {
        // 校验手机号
        boolean phoneInvalid = RegexUtils.isPhoneInvalid(phone);
        if (phoneInvalid) {
            // 手机号不符合规则，返回错误
            return Result.fail("手机号不符合规则！");
        }
        // 生成验证码
        String code = RandomUtil.randomNumbers(6);
        log.debug("生成验证码成功：{}", code);
        // 保存验证码至redis
        stringRedisTemplate.opsForValue().set(LOGIN_CODE_KEY + phone, code, LOGIN_CODE_TTL, TimeUnit.HOURS);

        return Result.ok();
    }

    /**
     * 登录或注册
     * @param loginForm
     * @param session
     * @return
     */
    @Override
    public Result login(LoginFormDTO loginForm, HttpSession session) {
        // 校验手机号
        String phone = loginForm.getPhone();
        boolean phoneInvalid = RegexUtils.isPhoneInvalid(phone);
        if (phoneInvalid) {
            // 手机号不符合规则，返回错误
            return Result.fail("手机号不符合规则！");
        }
        // 校验验证码
        String code = loginForm.getCode();
        String cacheCode = stringRedisTemplate.opsForValue().get(LOGIN_CODE_KEY + phone);
        if (cacheCode == null || !code.equals(cacheCode)) {
            // 验证码不正确，返回错误
            return Result.fail("验证码校验失败！");
        }
        // 判断当前用户是否存在
        User user = query().eq("phone", phone).one();
        if (user == null) {
            // 不存在则新增该用户
            user = createAndSave(phone);
        }

        // 将用户添加到redis中
        HashMap<String, String> userMap = new HashMap<>();
        userMap.put("id", String.valueOf(user.getId()));
        userMap.put("nickName", user.getNickName());
        userMap.put("icon", user.getIcon());
        String token = UUID.randomUUID().toString(true);
        String tokenKey = LOGIN_USER_KEY + token;
        stringRedisTemplate.opsForHash().putAll(tokenKey, userMap);
        stringRedisTemplate.expire(token, LOGIN_USER_TTL, TimeUnit.SECONDS);

        return Result.ok(token);
    }

    /**
     * 用户签到
     * @return
     */
    @Override
    public Result sign() {
        // 获取当前用户
        Long userId = UserHolder.getUser().getId();
        // 获取当前时间
        LocalDateTime now = LocalDateTime.now();
        String yAndM = now.format(DateTimeFormatter.ofPattern("yyyy/MM:"));
        int today = now.getDayOfMonth();
        // 创建bitmap的key
        String signKey = USER_SIGN_KEY + yAndM + userId;
        // 签到 SETBIT key offset value
        stringRedisTemplate.opsForValue().setBit(signKey, today - 1, true);

        return Result.ok();
    }

    /**
     * 统计当前用户截至目前当月连续签到次数
     * @return
     */
    @Override
    public Result signCount() {
        // 获取当前用户
        Long userId = UserHolder.getUser().getId();
        // 获取当前时间
        LocalDateTime now = LocalDateTime.now();
        String yAndM = now.format(DateTimeFormatter.ofPattern("yyyy/MM:"));
        int today = now.getDayOfMonth();
        // 创建bitmap的key
        String signKey = USER_SIGN_KEY + yAndM + userId;
        // 查询当前用户本月的签到情况 BITFIELD key GET utoday 0
        List<Long> signList = stringRedisTemplate.opsForValue().bitField(signKey, BitFieldSubCommands.create()
                .get(BitFieldSubCommands.BitFieldType.unsigned(today)).valueAt(0));
        // 无签到数据，返回0
        if (signList == null || signList.isEmpty()) {
            return Result.ok(0);
        }
        Long signConditions = signList.get(0);
        if (signConditions == null || signConditions == 0) {
            return Result.ok(0);
        }
        int count = 0;
        // 循环获取签到情况的最后一位，判断是否签到
        while (true) {
            if ((signConditions & 1) == 0) {
                // 若未签到，返回统计值
                return Result.ok(count);
            }
            // 若签到，统计值 +1
            count++;
            // 签到情况右移一位
            signConditions >>>= 1;
        }
    }

    /**
     * 创建并保存用户
     * @param phone
     * @return
     */
    private User createAndSave(String phone) {
        User user = new User();
        user.setPhone(phone);
        user.setNickName(USER_NICK_NAME_PREFIX + RandomUtil.randomString(10));
        user.setCreateTime(LocalDateTime.now());
        user.setUpdateTime(LocalDateTime.now());
        // 新增用户
        save(user);
        return user;
    }
}
